package cn.cubix.flow.config;

import cn.hutool.core.lang.generator.SnowflakeGenerator;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;

/**
 * SnowflakeId配置
 */
@Configuration
@RequiredArgsConstructor(onConstructor=@__({@Autowired,@Lazy}))
public class CusSnowflakeConfig {

    @Value("${spring.cache.level:None}")
    private String cacheLevel;
    @Value("${snowflake.datacenterid:0}")
    private int dataCenterId;
    @Value("${snowflake.workerid:0}")
    private int workerId;

    private final RedissonClient redissonClient;

    private boolean isRedisEnable(){
        return "L2".equals(cacheLevel)||"LR".equals(cacheLevel);
    }

    @Bean
    public SnowflakeGenerator snowflakeGenerator(){
        if(isRedisEnable()){
            int worker = 0;
            do{
                RLock lock = redissonClient.getLock("LOCK::SNOWFLAKE::"+dataCenterId+"_"+worker);
                if(lock.tryLock()){// 不释放锁，应用停止后WatchDog停止延期自动释放
                    return new SnowflakeGenerator(worker,dataCenterId);
                }
            } while(worker++>=0);
        }
        return new SnowflakeGenerator(workerId,dataCenterId);
    }

}
